<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 5] 5.3 Object Creation</TITLE>
<META NAME="author" CONTENT="Pat Niemeyer and Josh Peck">
<META NAME="date" CONTENT="Tue Jul 22 18:52:43 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Exploring Java">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Exploring Java" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_02.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 5<br>Objects in Java</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch05_04.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-3">5.3 Object Creation</A></h2>

<P CLASS=para>
Objects in Java are allocated from a system heap space, much like
<tt CLASS=literal>malloc</tt>'ed storage in C or C++. Unlike C or C++,
however, we needn't manage that memory ourselves. Java takes
care of memory allocation and deallocation for you. Java explicitly
allocates storage for an object when you create it with the
<tt CLASS=literal>new</tt> keyword. More importantly, objects are removed
by garbage collection when they're no longer referenced.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-3.1">Constructors</A></h3>

<P CLASS=para>
<A NAME="CH05.CONS1"></A><A NAME="CH05.CONS2"></A>You allocate an object by specifying the <tt CLASS=literal>new</tt> 
operator with an object <I CLASS=emphasis>constructor</I>. A constructor 
is a special method with the same name as its class and no return type. 
It's called when a new class instance is created, which gives the class 
an opportunity to set up the object for use. Constructors, like other methods, 
can accept arguments and can be overloaded (they are not, however, inherited 
like other methods; we'll discuss inheritance later).

<DIV CLASS=programlisting>
<P>
<PRE>
class Date { 
    long time; 
 
    Date() { 
        time = currentTime(); 
    } 
 
    Date( String date ) { 
        time = parseDate( date ); 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
In the above example, the class <tt CLASS=literal>Date</tt> has two
constructors. The first takes no arguments; it's known as the default
constructor. Default constructors play a special role in that, if we
don't define any constructors for a class, an empty default
constructor is supplied for us. The default constructor is what gets
called whenever you create an object by calling its constructor with
no arguments. Here we have implemented the default constructor so that
it sets the instance variable <tt CLASS=literal>time</tt> by calling a
hypothetical method: <tt CLASS=literal>currentTime()</tt>, which resembles
the functionality of the real <tt CLASS=literal>java.util.Date</tt> class.

<P CLASS=para>
The second constructor takes a <tt CLASS=literal>String</tt>
argument. Presumably, this <tt CLASS=literal>String</tt> contains a
string representation of the time that can be parsed to set the
<tt CLASS=literal>time</tt> variable.

<P CLASS=para>
Given the constructors above, we create a
<tt CLASS=literal>Date</tt> object in the following ways:

<DIV CLASS=programlisting>
<P>
<PRE>
Date now = new Date(); 
Date christmas = new Date("Dec 25, 1997"); 
</PRE>
</DIV>

<P CLASS=para>
In each case, Java chooses the appropriate constructor at compile-time 
based on the rules for overloaded method selection. 

<P CLASS=para>
If we later remove all references to an allocated object, it'll
be garbage collected, as we'll discuss shortly: 

<DIV CLASS=programlisting>
<P>
<PRE>
christmas = null;          // fair game for the garbage collector 
</PRE>
</DIV>

<P CLASS=para>
Setting the above reference to <tt CLASS=literal>null</tt> means it's no
longer pointing to the "Dec 25, 1997" object. Unless that
object is referenced by another variable, it's now inaccessible and
can be garbage collected. Actually, setting
<tt CLASS=literal>christmas</tt> to any other value would have the same
results, but using the value <tt CLASS=literal>null</tt> is a clear way to
indicate that <tt CLASS=literal>christmas</tt> no longer has a useful
value.

<P CLASS=para>
A few more notes about constructors. Constructors can't be
<tt CLASS=literal>abstract</tt>, <tt CLASS=literal>synchronized</tt>, or
<tt CLASS=literal>final</tt>. Constructors can, however, be declared with
the visibility modifiers public, private, or protected, to control their 
accessibility. We'll talk
in detail about visibility modifiers later in the chapter.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-3.2">Working with Overloaded Constructors</A></h3>

<P CLASS=para>
<A NAME="CH05.OVER3"></A><A NAME="CH05.OVER4"></A>A constructor can refer to another constructor in the same class or
the immediate superclass using special forms of the
<tt CLASS=literal>this</tt> and <tt CLASS=literal>super</tt>
references. We'll discuss the first case here, and return to
that of the superclass constructor again after we have talked more
about subclassing and inheritance.

<P CLASS=para>
<A NAME="CH05.THIS"></A>A constructor can invoke another, overloaded constructor in its class using 
the reference <tt CLASS=literal>this()</tt> with appropriate arguments 
to select the desired constructor. If a constructor calls another 
constructor, it must do so as its first statement (we'll explain 
why in a bit): 

<DIV CLASS=programlisting>
<P>
<PRE>
class Car { 
    String model; 
    int doors; 
 
    Car( String m, int d ) { 
        model = m; 
        doors = d; 
        // other, complicated setup 
        ... 
    } 
 
    Car( String m ) { 
        this( m, 4 ); 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
In the example above, the class <tt CLASS=literal>Car</tt> has two 
overloaded constructors. The first, more explicit one, accepts arguments 
specifying the car's model and its number of doors and uses them 
to set up the object. We have also provided a simpler constructor that 
takes just the model as an argument and, in turn, calls the first constructor 
with a default value of four doors. The advantage of this approach is that 
you can have a single constructor do all the complicated setup work; 
other auxiliary constructors simply feed the appropriate arguments to that 
constructor. 

<P CLASS=para>
The important point is the call to 
<tt CLASS=literal>this()</tt>, which must appear as the first 
statement our second constructor. The syntax is restricted in this way because
there's a need to identify a clear chain of command in the calling of
constructors. At one end of the chain, Java invokes the constructor of
the superclass (if we don't do it explicitly) to ensure that
inherited members are initialized properly before we proceed. There's
also a point in the chain, just after the constructor of the
superclass is invoked, where the initializers of the current
class's instance variables are evaluated. Before that point, we
can't even reference the instance variables of our class. We'll
explain this situation again in complete detail after we have talked
about inheritance.

<P CLASS=para>
For now, all you need to know is that you can invoke a second
constructor only as the first statement of another constructor. In
addition, you can't do anything at that point other than pass along
arguments of the current constructor. For example, the following is
illegal and causes a compile-time error:

<DIV CLASS=programlisting>
<P>
<PRE>
Car( String m ) { 
    int doors = determineDoors(); 
    this( m, doors );   // Error  
}                       // Constructor call must be first statement 
</PRE>
</DIV>

<P CLASS=para>
The simple model name constructor can't do any additional setup before 
calling the more explicit constructor. It can't even refer to an instance 
member for a constant value: 

<DIV CLASS=programlisting>
<P>
<PRE>
class Car {  
    ... 
    final int default_doors = 4; 
    ... 
 
    Car( String m ) { 
        this( m, default_doors ); // Error 
                                  // Referencing uninitialized variable 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
The instance variable <tt CLASS=literal>defaultDoors</tt> above is not 
initialized until a later point in the chain of constructor calls, so the 
compiler doesn't let us access it yet. Fortunately, we can solve this 
particular problem by making the identifier <tt CLASS=literal>static</tt> 
as well: 

<DIV CLASS=programlisting>
<P>
<PRE>
class Car { 
    ... 
    static final int DEFAULT_DOORS = 4; 
    ... 
 
    Car( String m ) { 
        this( m, DEFAULT_DOORS );  // Okay now 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
The <tt CLASS=literal>static</tt> members of our class have been initialized 
for some time (since the class was first loaded), so it's safe to access them. 

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-3.3">Static and Nonstatic Code Blocks</A></h3>

<P CLASS=para>
<A NAME="CH05.STATIC"></A><A NAME="CH05.STATIC2"></A>
It's possible to declare a code block (some statements within curly
braces) directly within the scope of a class. 
This code block doesn't belong to any method; instead, it's executed just
once, at the time the object is constructed, or, in the case of a code
block marked static, at the time the class is loaded.

<P CLASS=para>
Nonstatic code blocks can be thought of as just an extension of 
instance variable initialization.  They are called at the time the instance 
variable's initializers are evaluated (after superclass construction), in
the textual order in which they appear in the class source.

<DIV CLASS=programlisting>
<P>
<PRE>
class MyClass {
    Properties myProps = new Properties();
    // set up myProps
    {
        myProps.put("foo", "bar);
        myProps.put("boo", "gee);
    }
    int a = 5;
    ...
</PRE>
</DIV>

<P CLASS=para>

You can use static code blocks to initialize <tt CLASS=literal>static</tt>
class members in this way.  So the static members of a class can have 
complex initialization just like objects:

<DIV CLASS=programlisting>
<P>
<PRE>
class ColorWheel { 
    static Hashtable colors = new Hashtable(); 
 
    // set up colors
    static { 
        colors.put("Red", Color.red ); 
        colors.put("Green", Color.green ); 
        colors.put("Blue", Color.blue ); 
        ... 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
In the above example, the class <tt CLASS=literal>ColorWheel</tt> provides 
a variable <tt CLASS=literal>colors</tt> that maps the names of colors 
to <tt CLASS=literal>Color</tt> objects in a 
<tt CLASS=literal>Hashtable</tt>. 
The first time the class <tt CLASS=literal>ColorWheel</tt> 
is referenced and loaded, the <tt CLASS=literal>static</tt> components 
of <tt CLASS=literal>ColorWheel</tt> are evaluated, in the order 
they appear in the source. In this case, the <tt CLASS=literal>static</tt> 
code block simply adds elements to the <tt CLASS=literal>colors</tt> 
<tt CLASS=literal>Hashtable</tt>. 

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_02.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch05_04.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Methods</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Object Destruction</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
